package com.njust.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@RequestMapping("/file")
@Controller
public class FileUploadController {

    @RequestMapping("/upload")
    public String upload(@RequestParam(name = "username", required = false) String username,
                         @RequestParam("headerimg") MultipartFile file, Model model) {

        System.out.println("上传文件信息");
        System.out.println("上传文件名字：" + file.getName());
        System.out.println("上传文件名字：" + file.getOriginalFilename());
        File destFile = new File("C:/Users/Shisanyang/Desktop/aaa/test.png");
        //文件保存
        try {
            file.transferTo(destFile);
            model.addAttribute("singleFile", "文件上传成功");
        } catch (IOException e) {
            model.addAttribute("singleFile", "文件上传失败" + e.getMessage());
        }

        return "forward:/pages/jsp/upload.jsp";
    }


    @RequestMapping("/multipleFileUpload")
    public String upload(@RequestParam(name = "username", required = false) String username,
                         @RequestParam("headerimg") MultipartFile[] files, Model model) {

        for (int i = 0; i < files.length; i++) {
            if (!files[i].isEmpty()) {
                //文件保存
                File destFile = new File("C:/Users/Shisanyang/Desktop/aaa/" + files[i].getOriginalFilename());
                try {
                    files[i].transferTo(destFile);
                    model.addAttribute("multipleFile", "文件上传成功");
                } catch (IOException e) {
                    model.addAttribute("multipleFile", "文件上传失败" + e.getMessage());
                }
            }
        }
        return "forward:/pages/jsp/upload.jsp";
    }

}
